package office.stock.services;

import javax.ejb.EJB;
import javax.ejb.Singleton;

import office.stock.messaging.SubscribersRegistry;
import office.stock.messaging.WebsocketSubscriber;
import office.stock.messaging.notifications.NewOfferNotification;
import office.stock.messaging.notifications.Notification;
import office.stock.messaging.notifications.OfferClosedNotification;
import office.stock.messaging.notifications.OfferRemovedNotification;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Singleton
public class NotificationServiceImpl implements NotificationService {
    
    private final static Log log = LogFactory.getLog(NotificationServiceImpl.class);
    
    @EJB
    private SubscribersRegistry subscribersRegistry;
    
    @Override
    public void notifyUsers(OfferClosedNotification notification) {
	log.debug("Offer closed");
	sendNotification(notification);
    }

    @Override
    public void notifyUsers(NewOfferNotification notification) {
	sendNotification(notification);
    }

    @Override
    public void notifyUsers(OfferRemovedNotification offerRemovedNotification) {
	sendNotification(offerRemovedNotification);
    }

    private void sendNotification(Notification notification) {
	// TODO consider using for-join in order to achieve better performance
	for (WebsocketSubscriber subscriber : subscribersRegistry.getAll()) {
	    try {
		subscriber.notifyAsynchronously(notification);
	    } catch (Throwable exception) {
		log.error("Error occured while notifing used", exception);
	    }
	}
    }

}
